<?php

namespace app\admin\controller\rider;

use app\common\controller\Backend;
use app\common\model\User;
use function print_r;
use function str_replace;
use think\Db;
use Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use function var_dump;
use app\common\library\Sms;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Apply extends Backend
{
    
    /**
     * RideRapply模型对象
     * @var \app\admin\model\RiderApply
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\RiderApply;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as &$row) {
                $row['prefecture'] = str_replace('/','',$row['prefecture']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->with('user')->find($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($has = $this->model->where('user_id', $params['user_id'])->where('id', 'NEQ', $row->id)->count()) $this->error('当前选中用户已提交申请');
                $result = false;
                $status = $row->status;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    $model = new \app\common\model\User;

                    $user = $model->get($params['user_id']);
                    $user->allowField(true)->save([
                        'nickname'  => $params['apply_name'],
                        'mobile'    => $params['apply_mobile']
                    ]);
                    /*查询是否有选择的用户的申请信息*/
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    /*短信通知结果*/
                    if($row->status != $status){
                        if( $row->status == '1'){
                            //审核通过
                            $config = get_addon_config('alisms');
                            $alisms = new \addons\alisms\library\Alisms();
                            $alisms->mobile($row->apply_mobile)
                                ->template('SMS_218157064')
                                ->sign($config['sign'])
                                ->param(['name'=>$row->apply_name])
                                ->send();
                            $user = User::get($row->user_id);
                            if( $user->mobile =='') $user->allowField(true)->save(['mobile' => $row->apply_mobile]);
                        }
//                        if( $params['status'] == '1'){
//                            //审核通过
//                            Sms::send($row->apply_mobile, $row->apply_name, 'applyNotice');
//                        }
                    }
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty',''));
        }
        $this->view->assign("ridertypelist", [
            '司机','普通骑手','业务员'
        ]);
        $prefecture = str_replace("西藏","西藏/", $row->prefecture);
        $prefecture = str_replace("宁夏","宁夏/", $row->prefecture);
        $prefecture = str_replace("新疆","新疆/", $row->prefecture);
        $prefecture = str_replace("香港特别行政区","香港特别行政区/", $row->prefecture);
        $prefecture = str_replace("澳门特别行政区","澳门特别行政区/", $row->prefecture);
        $prefecture = str_replace("台湾","台湾/", $row->prefecture);
        $prefecture = str_replace("省","省/", $row->prefecture);
        $prefecture = str_replace("市","市/", $prefecture);
        $prefecture = rtrim ( $prefecture ,  "/" );
        $row->prefecture = $prefecture;
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                if($has = $this->model->where('user_id', $params['user_id'])->count()) $this->error('当前选中用户已提交申请');
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    $result = $this->model->allowField(true)->save($params);
                    $user = new User($params['user_id']);
                    print_r($user->nickname);die;
                    $user->nickname = $params['apply_name'];
                    $user->mobile = $params['apply_mobile'];
//                    $user->allowField(true)->save([
//                        'nickname'  => $params['apply_name'],
//                        'mobile'    => $params['apply_mobile']
//                    ]);
                    $user->save();
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("ridertypelist", [
            '司机','普通骑手','业务员'
        ]);
        return $this->view->fetch();
    }
}
